package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.pojo.Customerpreference;
import com.neudu.yiyang.service.CustomerpreferenceService;
import com.neudu.yiyang.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CustomerpreferenceController {

    @Autowired
    private CustomerpreferenceService customerpreferenceService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private JSONReturn jsonReturn;

    //分页查询膳食喜好
    @RequestMapping("get_customer_preferences_with_name")
    public String getPreferencesWithCustomerName(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(required = false) String keyword
    ) {
        try {
            // 开启分页
            PageHelper.startPage(pageNum, pageSize);
            // 确保查询时过滤掉 is_deleted = 1 的记录
            List<Map<String, Object>> preferenceList = customerpreferenceService.selectWithCustomerNameAndFilterDeleted(keyword);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(preferenceList);
            Map<String, Object> result = new HashMap<>();
            result.put("pageNum", pageInfo.getPageNum());
            result.put("pageSize", pageInfo.getPageSize());
            result.put("total", pageInfo.getTotal());
            result.put("list", pageInfo.getList());
            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 根据ID查询单个膳食喜好（含客户姓名）
     */
    @RequestMapping("get_preference_by_id")
    public String getPreferenceById(@RequestParam Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }
            Map<String, Object> preference = customerpreferenceService.selectByIdWithCustomerName(id);
            return jsonReturn.returnSuccess(preference);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 根据客户ID从customer表中获取客户姓名
     */
    @RequestMapping("get_customer_name_by_id_from_customer")
    public String getCustomerNameByIdFromCustomer(@RequestParam Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }
            Customer customer = customerService.getById(id);
            if (customer == null) {
                return jsonReturn.returnError("客户ID在客户表中不存在");
            }
            Map<String, Object> result = new HashMap<>();
            result.put("customer_name", customer.getCustomerName());
            return jsonReturn.returnSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 新增膳食喜好
     */
    @PostMapping("add_customer_preference")
    public Object addPreference(@RequestBody Customerpreference customerpreference) {
        try {
            Integer customerId = customerpreference.getCustomerId();
            if (customerId == null) {
                return jsonReturn.returnError("客户ID不能为空");
            }

            Customer customer = customerService.getById(customerId);
            if (customer == null) {
                return jsonReturn.returnError("客户ID在客户表中不存在");
            }

            // 检查客户状态是否为已退住
            if (customer.getStatus() != null && customer.getStatus() == 1) {
                return jsonReturn.returnError("该客户已退住，无法添加膳食喜好");
            }

            // 确保设置正确的喜好和备注
            customerpreference.setPreferences(customerpreference.getPreferences()); // 假设前端已经提供了喜好的值
            customerpreference.setRemark(customerpreference.getRemark()); // 假设前端已经提供了备注的值
            customerpreference.setIsDeleted(0);

            boolean success = customerpreferenceService.save(customerpreference);
            if (success) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    /**
     * 修改膳食喜好
     */
    @RequestMapping("update_customer_preference")
    public String updatePreference(@RequestBody Customerpreference customerpreference) {
        try {
            if (customerpreference.getId() == null) {
                return jsonReturn.returnError("ID不能为空");
            }
            // 检查记录是否存在（逻辑删除标记为0）
            LambdaQueryWrapper<Customerpreference> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Customerpreference::getId, customerpreference.getId())
                    .eq(Customerpreference::getIsDeleted, 0);
            Customerpreference existingPreference = customerpreferenceService.getOne(queryWrapper);
            if (existingPreference == null) {
                return jsonReturn.returnError("记录不存在或已删除");
            }
            boolean success = customerpreferenceService.updateById(customerpreference);
            if (success) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    /**
     * 删除膳食喜好（逻辑删除）
     */
    @RequestMapping("delete_preference_by_id")
    public String deletePreference(@RequestParam Integer id) {
        try {
            if (id == null) {
                return jsonReturn.returnError("ID不能为空");
            }
            Customerpreference preference = new Customerpreference();
            preference.setId(id);
            preference.setIsDeleted(1); // 设置逻辑删除标记为1（隐藏）
            boolean success = customerpreferenceService.updateById(preference);
            if (success) {
                return jsonReturn.returnSuccess();
            } else {
                return jsonReturn.returnError("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}